package com.endava.graduates.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.endava.graduates.model.LoginForm;
import com.endava.graduates.model.User;
import com.endava.graduates.service.UserService;

@Controller
@RequestMapping("/")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "user.html", method = RequestMethod.GET)
	public String getAllUsers(Model model) {

		List<User> users = userService.getAllUsers();
		model.addAttribute("users", users);
		return "user";

	}

//	@RequestMapping(value = "login.html", method = RequestMethod.GET)
//	public String login(Model model) {
//
//		User user = userService.getUserByUsername();
//		return "login";
//
//	}

	@RequestMapping(value = "login.html", method = RequestMethod.GET)
	public String showForm(ModelMap model) {

		LoginForm login = new LoginForm();
		//User login = new User();
		model.addAttribute("login", login);
		return "login";

	}

	@RequestMapping(value = "login.html", method = RequestMethod.POST)
	public String processForm(@ModelAttribute(value = "login") LoginForm login, BindingResult result, ModelMap model) {

		//System.out.println("User values is : " + user.getUsername());
		User dbUser = userService.getUserByUsername(login.getUsername());
		System.out.println("db username: "+dbUser);
		if (result.hasErrors()) {

			return "login";

		} else if(dbUser!=null) {

			System.out.println("Form values  : " + login);
			String userName = dbUser.getFirstName()+" "+dbUser.getLastName();
			model.addAttribute("name", userName);
			return "success";

		}
		else {
			model.addAttribute("inexistentuser", "The username is not correct");
			return "login";
		}

	}

	public UserService getUserService() {
		return userService ;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
